# -*- coding: utf-8 -*-

from openerp.osv import osv, fields
from openerp import tools
from openerp import models,api,SUPERUSER_ID,_
import datetime

#产品增加‘代理商售价’和‘产品分类‘两个字段
class product_product(osv.osv):
    _inherit = "product.template"
    _columns = {
        'agents_price':fields.float(u'代理商给下级客户的价格'),
        'categ_id': fields.many2one('product.category','产品分类', required=True, change_default=True, domain="[('type','=','normal')]"),
    	}

#卡券归属索引表增加’是否激活‘字段，与product.card.line中的'card_line_id'字段相关联
class product_card_index(osv.osv):
    _inherit="product.card.index"
    _columns={
              'is_active': fields.related('card_line_id','is_active',string=u'是否激活',type='boolean',readonly='1'),
              }

#代理商销售订单表，分为铺券订单和激活订单
class agents_order(osv.osv):
    _name = 'agents.order'
    _rec_name = 'order_number'

    #代理商订单状态
    def _get_order_state(self,cr,uid,context=None):
        return [
            ('draft',u'草稿'),
            ('confirm',u'确认'),
            ('sent',u'已发货'),
            ('paid',u'已收款'),
            ('done',u'完成'),
        ]

    #代理商可以删除草稿状态下的订单
    def unlink(self, cr, uid, ids, context=None):
        for sale_orders in self.browse(cr, uid, ids, context=context):
            if sale_orders.state not in ['draft']:
                raise osv.except_osv(u'警告!', u'您不能删除非草稿状态下的销售订单!')
        return super(agents_order, self).unlink(cr, uid, ids, context=context)

    def confirm_button(self,cr,uid,ids,context=None):
        '''代理商卡券销售订单确认按钮'''
        issue_obj = self.pool.get('product.card.issue')
        line_obj = self.pool.get('product.card.line')
        index_obj=self.pool.get('product.card.index')
        user_obj = self.pool.get('res.users')
        res_partner_obj = self.pool.get('res.partner')
        user = user_obj.browse(cr, uid, uid, context=context)
        for order in self.browse(cr,uid,ids,context=context):
            for line in order.order_line:
                #验证卡券产品订单行都输入了卡券起始号码
                if not line.copy_card_start_number:
                    raise osv.except_osv(u'错误',u'卡券产品必须输入起始卡号') 
                #（在agents_order_line中的on_change_card已经验证了卡券起始号码已存在）验证起始号码及数量包含的卡号都存在
                codes = issue_obj.get_exist_codes(cr,uid,line.product_id,line.copy_card_start_number,abs(line.quantity))
                if len(codes) != abs(line.quantity):
                    raise osv.except_osv(u'错误',u'输入的卡券数量和存在的卡券数量不符，请检查后重新输入！')
                for code in codes:
                    line_obj_id=line_obj.search(cr, uid, [('code','=',code)],context=context)
                    line_obj_card=line_obj.browse(cr,uid,line_obj_id,context=context)
                    res_partner_one = res_partner_obj.browse(cr,uid,line_obj_card.level_one_partner_id.id,context)
                    res_partner_two = res_partner_obj.browse(cr,uid,line_obj_card.level_two_partner_id.id,context)
                    res_partner_owner = res_partner_obj.browse(cr,uid,line_obj_card.owner_id.id,context)
                    if line_obj_card.product_id.id != line.product_id.id:
                        raise osv.except_osv(u'错误',u'卡券产品和卡券号码不匹配，请重新输入')
                    if line.quantity > 0:
                        if line_obj.search(cr, uid, [('code','=',code),('level_one_partner_id','!=',user.partner_id.id)],context=context):
                            raise osv.except_osv(u'错误',u'卡券' + code + u'不属于当前用户')
                        if index_obj.search(cr, uid, [('code','=',code),('owner_id','=',res_partner_two.id)],context=context):
                            raise osv.except_osv(u'错误',u'卡券' +  code  + u'已经售出,请重新输入！')   
                    else:
                        if not line_obj_card.level_two_partner_id:
                            raise osv.except_osv(u'错误',u'卡券' +  code  + u'已被操作退回不可进行重复操作！')
                        if line_obj_card.owner_id.id == line_obj_card.level_one_partner_id.id:
                             raise osv.except_osv(u'错误',u'卡券' +  code  + u'已被代理商售出，请代理商下负数的激活订单退回后，才可以对本订单进行操作!')
                    if line_obj.search(cr, uid, [('code','=',code),('is_active','!=',True)],context=context):
                        raise osv.except_osv(u'错误',u'卡券' + code + u'未激活，激活后才能销售')
        self.write(cr,uid,ids,{'state':'confirm'},context=context)

    #发货后，提供“撤回成草稿”的功能按钮
    def confirm_back(self,cr,uid,ids,context=None):
        self.write(cr,uid,ids,{'state':'draft'},context=context)

    #“确认”按钮的处理逻辑
    def confirm_card_button(self,cr,uid,ids,context=None):
        '''代理商卡券铺券订单确认'''
        issue_obj = self.pool.get('product.card.issue')
        line_obj = self.pool.get('product.card.line')
        index_obj=self.pool.get('product.card.index')
        user_obj = self.pool.get('res.users')
        res_partner_obj = self.pool.get('res.partner')
        user = user_obj.browse(cr, uid, uid, context=context)
        for order in self.browse(cr,uid,ids,context=context):
            for line in order.order_line:
                #验证卡券产品订单行都输入了卡券起始号码
                if not line.copy_card_start_number:
                    raise osv.except_osv(u'错误',u'卡券产品必须输入起始卡号') 
                #（在agents_order_line的on_change_card已经验证了卡券起始号码已存在）,验证起始号码及数量包含的卡号都存在
                codes = issue_obj.get_exist_codes(cr,uid,line.product_id,line.copy_card_start_number,abs(line.quantity))
                if len(codes) != abs(line.quantity):
                    raise osv.except_osv(u'错误',u'输入的卡券数量和存在的卡券数量不符，请检查后重新输入！')
                for code in codes:
                    line_obj_id=line_obj.search(cr, uid, [('code','=',code)],context=context)
                    line_obj_card=line_obj.browse(cr,uid,line_obj_id,context=context)
                    res_partner_one = res_partner_obj.browse(cr,uid,line_obj_card.level_one_partner_id.id,context)
                    res_partner_two = res_partner_obj.browse(cr,uid,line_obj_card.level_two_partner_id.id,context)
                    res_partner_owner = res_partner_obj.browse(cr,uid,line_obj_card.owner_id.id,context)
                    if line_obj_card.product_id.id != line.product_id.id:
                        raise osv.except_osv(u'错误',u'卡券产品和卡券号码不匹配，请重新输入！')
                    if line.quantity > 0: 
                        #if line_obj.search(cr, uid, [('code','=',code),('level_two_partner_id','!=',False)],context=context): 
                            #raise osv.except_osv(u'错误',u'卡券' + code + u'已经售出，请重新输入！')                                          
                        if index_obj.search(cr, uid, [('code','=',code),('owner_id','=',res_partner_one.id),('is_sold_out','=',True)],context=context):
                            raise osv.except_osv(u'错误',u'卡券' + code + u'已经售出，请重新输入！')
                    if line_obj.search(cr, uid, [('code','=',code),('level_one_partner_id','!=',user.partner_id.id)],context=context):
                        raise osv.except_osv(u'错误',u'卡券' + code + u'不属于当前用户')
        self.write(cr,uid,ids,{'state':'confirm'},context=context)
        
    def send_button(self,cr,uid,ids,context=None):
        '''代理商卡券激活销售订单发货'''
        issue_obj = self.pool.get('product.card.issue')
        card_line_obj = self.pool.get('product.card.line')
        card_index_obj = self.pool.get('product.card.index')
        card_track_obj = self.pool.get('product.card.track')
        res_partner_obj = self.pool.get('res.partner')
        now_date = datetime.datetime.strptime(fields.datetime.now(), '%Y-%m-%d %H:%M:%S')
        for order in self.browse(cr,uid,ids,context=context):
            #判断是否已付款，如果已付款则订单完成,并写入发货时间;如果没付款，则修改订单状态为已发货，并写入发货时间
            if order.is_paid :
                self.write(cr,uid,ids,{'is_sent':'True','state':'done','send_date':now_date},context=context)
            else: 
                self.write(cr,uid,ids,{'is_sent':'True','state':'sent','send_date':now_date},context=context);
            
            for line in order.order_line:
                codes = issue_obj.get_exist_codes(cr,uid,line.product_id,line.copy_card_start_number,abs(line.quantity))
                for code in codes:
                    card_line_id = card_line_obj.search(cr,uid,[('code','=',code), '|', ('active', '=', False), ('active', '=', True)],context=context)[0]
                    card_line = card_line_obj.browse(cr,uid,card_line_id,context=context)
                    res_partner_one = res_partner_obj.browse(cr,uid,card_line.level_one_partner_id.id,context)
                    res_partner_two = res_partner_obj.browse(cr,uid,card_line.level_two_partner_id.id,context)
                    res_partner_owner = res_partner_obj.browse(cr,uid,card_line.owner_id.id,context) 
                    card_index_id = card_index_obj.search(cr,uid,[('code','=',code),('owner_id','=',card_line.owner_id.id)],context=context)[0]
                    card_index =  card_index_obj.browse(cr,uid,card_index_id,context=context) 
                    card_index_id_new=card_index_obj.search(cr,uid,[('owner_id','=',res_partner_two.id),('code','=',code),],context=context)
                    card_index_new = card_index_obj.browse(cr,uid,card_index_id_new,context=context)                    
                    #判断订单行表中的卡券是否有已经售出给相应的客户
                    if card_line_obj.search(cr, uid, [('code','=',code),('level_two_partner_id','!=',order.customer.id), '|', ('active', '=', False), ('active', '=', True)],context=context):
                        raise osv.except_osv(u'错误',u'卡券' +  code  + u'已经铺券给<' + res_partner_two.name +u'>,请重新输入！')    
                    if line.quantity < 0:
                        if card_line_obj.search(cr,uid, [('code','=',code),('owner_id','!=',order.customer.id), '|', ('active', '=', False), ('active', '=', True)],context=context):
                            raise osv.except_osv(u'错误',u'卡券' +  code  + u'该卡券归属方为<' + res_partner_owner.name +u'>,请检查退货用户输入正确后再进行退货操作！')
                        if card_index_obj.search(cr, uid, [('code','=',code),('owner_id','=',res_partner_one.id),('is_sold_out','=',True)],context=context):
                            #此卡券被铺券出货过，所以退货删除card_index表及line表level_two_partner_id为空和owner_id变回代理商。
                            card_index_obj.unlink(cr,uid,card_index_new.id,context=context)
                            card_line.write({'owner_id':res_partner_one.id})     
                        else:
                            #此卡券未铺券过，所以退货修改card_line表，更新level_two_partner_id为空和owner_id变回代理商
                            card_line.write({'level_two_partner_id':'','owner_id':res_partner_one.id})                       
                            #新建card_track表，记录owner变更
                            card_track_obj.create(cr,uid,{'card_line_id':card_line.id,'code':code,'operation_type':'back','old_owner_id':order.customer.id,'new_owner_id':res_partner_one.id,},context=context)                                                                                      
                    else:
                        #更新card_line表，更新owner_id
                        card_line.write({'owner_id': order.customer.id, 'level_two_partner_id': order.customer.id})    
                        #卡券激活销售的时候不更新card_index表归属方为代理商的数据，也不需要更改售出状态。
                        #card_index.write({'is_sold_out':True})                    
                        #新建card_index表，记录owner变更
                        card_index_obj.create(cr,uid,{'owner_id':order.customer.id,'product_id':card_line.product_id.id,'card_line_id':card_line.id,'code':code,'is_sold_out':False,'buy_price':line.unit_price,},context=context)                    
                        #新建card_track表，记录owner变更
                        card_track_obj.create(cr,uid,{'card_line_id':card_line.id,'code':code,'operation_type':'sold','old_owner_id':res_partner_one.id,'new_owner_id':order.customer.id,'buy_price':line.unit_price,},context=context)                                                                   
    
    def send_card_button(self,cr,uid,ids,context=None):
        '''代理商卡券铺券销售订单发货'''       
        issue_obj = self.pool.get('product.card.issue')
        card_line_obj = self.pool.get('product.card.line')
        card_index_obj = self.pool.get('product.card.index')
        card_track_obj = self.pool.get('product.card.track')
        res_partner_obj = self.pool.get('res.partner')
        for order in self.browse(cr,uid,ids,context=context):
            if order.is_paid :
                self.write(cr,uid,ids,{'is_sent':'True','state':'done'},context=context)
            else: 
                self.write(cr,uid,ids,{'is_sent':'True','state':'sent','send_date':datetime.datetime.strptime(fields.datetime.now(), '%Y-%m-%d %H:%M:%S')},context=context);
            
            for line in order.order_line:
                codes = issue_obj.get_exist_codes(cr,uid,line.product_id,line.copy_card_start_number,abs(line.quantity))
                for code in codes:
                    card_line_id = card_line_obj.search(cr,uid,[('code','=',code), '|', ('active', '=', False), ('active', '=', True)],context=context)[0]
                    card_line = card_line_obj.browse(cr,uid,card_line_id,context=context)
                    res_partner_one = res_partner_obj.browse(cr,uid,card_line.level_one_partner_id.id,context)
                    res_partner_two = res_partner_obj.browse(cr,uid,card_line.level_two_partner_id.id,context)
                    res_partner_owner = res_partner_obj.browse(cr,uid,card_line.owner_id.id,context) 
                    card_index_id = card_index_obj.search(cr,uid,[('code','=',code),('owner_id','=',res_partner_one.id)],context=context)[0]
                    card_index =  card_index_obj.browse(cr,uid,card_index_id,context=context)

                    if line.quantity > 0:
                        #if card_line_obj.search(cr, uid, [('code','=',code),('level_two_partner_id','!=',False)],context=context): 
                            #raise osv.except_osv(u'错误',u'卡券' + code + u'已经售出，请重新输入！') 
                        if card_index_obj.search(cr, uid, [('code','=',code),('owner_id','=',res_partner_one.id),('is_sold_out','=',True)],context=context):
                            raise osv.except_osv(u'错误',u'卡券' + code + u'已经售出，请重新输入！') 
                        if card_line_obj.search(cr,uid, [('code','=',code),('level_two_partner_id','!=',order.customer.id)],context=context):
                            raise osv.except_osv(u'错误',u'卡券' +  code  + u'该卡券激活用户为<' + res_partner_two.name +u'>,请检查用户输入正确后再进行铺券操作！')          
                        #更新card_line表，更新level_two_partner_id
                        card_line.write({'level_two_partner_id': order.customer.id})                                                              
                        #更新card_index表，更改售出状态
                        card_index.write({'is_sold_out':True,})  
                                                   
                    if line.quantity < 0:
                        if card_line_obj.search(cr,uid, [('code','=',code),('level_two_partner_id','!=',order.customer.id)],context=context):
                            raise osv.except_osv(u'错误',u'卡券' +  code  + u'该卡券铺券用户为<' + res_partner_two.name +u'>,请检查退货用户输入正确后再进行退货操作！')
                        if card_index_obj.search(cr, uid, [('code','=',code),('owner_id','=',res_partner_one.id),('is_sold_out','=',False)],context=context):
                            raise osv.except_osv(u'错误',u'卡券' + code + u'没有铺券不能退货，请重新输入！')
                        if not card_index_obj.search(cr, uid, [('code','=',code),('owner_id','=',res_partner_two.id),],context=context):
                            #铺券退货订单先检查该卡券是否有激活销售订单存在，如果不存在，更新card_line表level_two_partner_id为空和owner_id变回代理商。
                            card_line.write({'level_two_partner_id':'','owner_id':res_partner_one.id})
                            #更新card_index表，更改售出状态为false
                            card_index.write({'is_sold_out':False,})
                        else:
                            #有激活销售订单存在的情况则只更新index表。
                            card_index.write({'is_sold_out':False,})                        

    '''
    代理商订单中付款按钮
    当付款和发货都完成的时候，修改状态为完成。若没有发货只是将状态更改为已付款
    '''
    def pay_button(self,cr,uid,ids,context=None):
        for order in self.browse(cr,uid,ids,context=None):
            if order.is_sent:
                self.write(cr,uid,ids,{'is_paid':'True','state':'done'},context=context)
            else:
                self.write(cr,uid,ids,{'is_paid':'True','state':'paid'},context=context)

    #重载create方法，根据ir.sequence中的序列给订单号编号
    def create(self, cr, uid, vals, context=None):
        if vals.get('order_number','/') == '/':
            vals['order_number'] = self.pool.get('ir.sequence').get(cr, uid, 'agents.order') or '/'
        new_id =super(agents_order,self).create(cr, uid, vals, context=context)
        return new_id

    #_is_order_reject该字段所调用的方法，当输入产品数量为负数时，表示退货
    def _is_order_reject(self,cr,uid,ids,name,arg,context=None):
        res = {}
        for order in self.browse(cr,uid,ids,context=context):
            for order_lines in order.order_line:
                if order_lines.quantity < 0:
                    res[order.id] = True
        return res

    def print_agents_quotation(self, cr, uid, ids, context=None):
        ''' 该方法用来打印代理商的报价单和销售订单  '''
        assert len(ids) == 1, '该项每次只能使用一个id'
        return self.pool['report'].get_action(cr, uid, ids, 'agents_sale_order_lodop', context=context)
       
    _columns = {
        'order_number':fields.char(u'订单编号',required = True, copy = False,select=True),
        'customer':fields.many2one('res.partner',u'客户',required = True),
        'order_date':fields.date(u'订单日期'),
        'is_sent':fields.boolean(u'已发货'),
        'is_paid':fields.boolean(u'已付款'),
        'order_line':fields.one2many('agents.order.line','order_id',u'订单行表'),
        'state':fields.selection(_get_order_state,u'状态'),
        'is_order_reject':fields.function(_is_order_reject,string='是否退货',type='boolean',store=True),
        'send_date':fields.datetime('发货日期', readonly=True),
        'remarks':fields.text(string='备注'),
        'shop_coupons_order':fields.boolean(u'铺券订单'),
        'active_order':fields.boolean(u'激活订单'),
    }

    _defaults = {
        'order_number': lambda obj, cr, uid, context: '/',
        'state':'draft',
        'order_date':fields.date.context_today,
        #根据portal_channel_view.xml传的context值来给下面两个字段赋值
        'shop_coupons_order': lambda self,cr,uid,context: context.get('default_shop_coupons_order'),
        'active_order': lambda self,cr,uid,context: context.get('default_active_order'),
    }
	
#代理商销售行表
class agents_order_line(osv.osv):
    _name = 'agents.order.line'

    #将产品的代理商价格onchange返回 agents_order_line界面上
    def on_change_product_id(self,cr,uid,ids,product_id,context=None):
        product_obj = self.pool.get('product.product')
        price = product_obj.browse(cr,uid,product_id,context=context).agents_price
        return {'value':{'unit_price':price}}

    #校验输入的起始卡券号码是否存在
    def on_change_card(self,cr,uid,ids,copy_card_start_number,context = None):
        if copy_card_start_number:
            copy = self.pool.get('product.card.line').search(cr,uid,[('code','=',copy_card_start_number)])
            if not copy:
                raise osv.except_osv(u'错误',u'此起始卡券号不存在！')
            return {'value':{'card_start_number':copy}} 

    #在界面显示卡券结束号码
    def onchange_number_end(self,cr,uid,ids,copy_card_start_number,quantity,context = None):
        if copy_card_start_number:
            copy = self.pool.get('product.card.line').search(cr,uid,[('code','=',copy_card_start_number)])
            if not copy:
                raise osv.except_osv(u'错误',u'此起始卡券号不存在！')
        if not copy_card_start_number or not quantity:
            return {}
        abs_quantity = abs(quantity)
        number_end = self.pool['product.card.issue'].get_next_n_number(cr, copy_card_start_number,abs_quantity-1)
        return {'value':{'card_end_number':number_end}} #取完整结束卡券

    #计算价格总计
    def _get_total_price(self,cr,uid,ids,name,arg,context=None):
        res = {}
        for order_line in self.browse(cr,uid,ids,context=context):
            total_price = order_line.quantity * order_line.unit_price
            res.update({order_line.id:total_price})
        return res

    _columns = {
        'order_id':fields.many2one('agents.order',u'订单编号',ondelete='cascade'),
        'product_id':fields.many2one('product.product',u'产品',required=True),
        'card_start_number':fields.many2one('product.card.line',u'卡券起始号码',domain="[('is_active','=',True),('product_id','=',product_id)]"),
        'copy_card_start_number':fields.char(u'卡券起始号码'),
        'card_end_number':fields.char(u'卡券结束号码'),
        'quantity':fields.integer(u'数量',required=True),
        'unit_price':fields.float(u'单价'),
        'total_price':fields.function(_get_total_price,string='合计',type='float',store=True),
        
    }
#在客户上增加 代理商应收款合计 字段，另外再加一个代理商创建字段，区分客户是代理商创建的还是内部创建的 
class res_partner(osv.osv):
    _inherit = 'res.partner'
    
    _columns = {
        'agents_receivables_total':fields.float(u'代理商应收款合计'),
        'create_by_agents':fields.boolean(u'代理商创建',readonly=True),
        'company_partner_id': fields.many2one('res.partner',u'所属父级公司'),
    }
    _defaults = {
        'create_by_agents': lambda self,cr,uid,context: context.get('by_agents'),# 判断客户是代理商创建的还是内部创建的 
        'company_partner_id': lambda self,cr,uid,context: context.get('company_partner_id'),#默认所属公司
    }

#客户应收款明细：日期，客户，增加（float），减少（float），余额（float）
class agents_receivables_line(osv.osv):
    _name = 'agents.receivables.line'
    _columns = {
        'date':fields.date(u'日期'),
        'partner_id':fields.many2one('res.partner',u'客户'),
        'debit':fields.float(u'增加'),
        'credit':fields.float(u'减少'),
        'balance':fields.float(u'余额'),
    }

    #重载create方法，将客户应收款的信息更新到res.partner表中
    def create(self, cr, uid, vals, context=None):
        partner_obj = self.pool.get('res.partner')
        partner = partner_obj.browse(cr,uid,vals['partner_id'],context=context)
        balance = partner.agents_receivables_total + vals.get('debit',0.0) - vals.get('credit',0.0)
        partner.write({'agents_receivables_total':balance})
        vals.update({'balance':balance})
        return super(agents_receivables_line,self).create(cr, uid, vals, context=context) 

#代理商的经手卡券批量激活向导
class agents_active_wizard(models.TransientModel):
    _name = 'agents.active.wizard'
    _description = u'代理商的经手卡券表中选中多条记录进行批量激活'

    #调用active.wizard的get_message，获得报错信息
    def get_message(self,cr,uid,context=None):
        line_ids = []
        for index in self.pool.get('product.card.index').browse(cr, uid, context.get('active_ids'),context=context):
            line_ids.append(index.card_line_id.id)
        return self.pool['active.wizard'].get_message(cr,uid,context=context,line_ids = line_ids)

    _columns={
            'confirm_message': fields.text(u'激活时确认',readonly=True),
            }    
    _defaults = {
                'confirm_message': get_message,
                }

    #激活勾选的卡券，若报错返回报错信息
    def do_active(self,cr,uid,ids,context=None):
        line_ids = []
        for index in self.pool.get('product.card.index').browse(cr, uid, context.get('active_ids'),context=context):
            line_ids.append(index.card_line_id.id)
        message = self.pool['product.card.line'].do_active(cr,SUPERUSER_ID,line_ids,context=context)
        if message:
            raise osv.except_osv(u'警告！',message)
        return True   

''' 代理商取消激活暂时不需要 '''
# class agents_deactive_wizard(models.TransientModel):
#     _name = 'agents.deactive.wizard'
#     _description = u'代理商的经手卡券表中选中多条记录进行批量取消激活'
# 
#     def get_message(self,cr,uid,context=None):
#         line_ids = []
#         for index in self.pool.get('product.card.index').browse(cr, uid, context.get('active_ids'),context=context):
#             line_ids.append(index.card_line_id.id)
#         return self.pool['deactive.wizard'].get_message(cr,uid,context=context,line_ids = line_ids)
#     _columns={
#             'confirm_message': fields.text(u'取消激活时确认',readonly=True),
#             }    
#     _defaults = {
#                 'confirm_message': get_message,
#                 }
#     #取消激活勾选的卡券，若报错返回报错信息
#     def do_deactive(self,cr,uid,ids,context=None):
#         line_ids = []
#         for index in self.pool.get('product.card.index').browse(cr, uid, context.get('active_ids'),context=context):
#             line_ids.append(index.card_line_id.id)
#         message = self.pool['product.card.line'].do_deactive(cr,SUPERUSER_ID,line_ids,context=context)
#         if message:
#             raise osv.except_osv(u'警告！',message) 
#         return True

class channel_active_wizard(models.TransientModel):
    _name = 'channel.active.wizard'
    _description = u'代理商输入一批卡券进行激活操作'
    _columns={
              'active_number':fields.text(u'需要激活的卡券'), 
              'check_active':fields.text(u'卡券号确认',readonly=False),
            }
    def check_active_number(self,cr,uid,ids,active_number,context=None): 
        '''on_change校验左边输入的卡券号是否正确，若不正确在右边文本框会提示修改
                      若输入全部正确，这显示需要激活卡券的详情'''
        if active_number :
            card_line_obj=self.pool.get('product.card.line')
            user_obj=self.pool.get('res.users').browse(cr,uid,uid,context)
            res = '' #存放报错提示的字符串
            code_line='' #用来装填校验输入的卡券号无错误之后的提示
            line_ids = [] #根据一个卡券号取得的id列表
            line_idss=[] #全部检查通过的卡券id，组成数列
            codes = []  #从输入的text中，转成tuple后拿到的卡券号列表
            rows_tup = []  #每个卡券号对应的行号                
            codes.extend(self.parse_text(cr, active_number))
            for i in range(len(codes)):
                code_tup=codes[i][1] #券号
                rows_tup=codes[i][0] #行号
                line_ids=card_line_obj.search(cr,uid,[('code','=',code_tup)],context=context)
                if not line_ids:
                    res = '第'+ str(rows_tup) +'行'+','+'卡券'+code_tup +'不存在'
                    return {'value':{'check_active':res}}                             
                for line_id in card_line_obj.browse(cr,uid,line_ids,context=context):
                    if line_id.is_active==True:
                        res = '第'+ str(rows_tup) +'行'+','+'卡券'+ line_id.code +'已激活'
                        return {'value':{'check_active':res}}
                    if line_id.is_enabled==False:
                        res = '第'+ str(rows_tup) +'行'+','+'卡券'+ line_id.code +'还未启用不能激活，请先启用！'
                        return {'value':{'check_active':res}}
                    if line_id.owner_id.id==user_obj.company_id.partner_id.id:
                        res = '第'+ str(rows_tup) +'行'+','+'卡券'+ line_id.code +'归属方还是发行方，不可激活!'
                        return {'value':{'check_active':res}}
                    #如果当前用户是个代理商，那么判断卡券的归属方是否是当前用户对应的代理商
                    if user_obj[0].has_group('dzx_ext.group_agents'):
                        if line_id.owner_id.id != user_obj[0].partner_id.id:
                            res = '第'+ str(rows_tup) +'行'+','+'卡券'+ line_id.code +'不属于您，不可激活!'
                            return {'value':{'check_active':res}}
                line_idss.extend(line_ids)
            code_line=self.pool['active.wizard'].get_message(cr,uid,context=context,line_ids=line_idss) 
            return {'value':{'check_active':code_line}}
    
    def fields_view_get(self, cr, uid, view_id=None, view_type='form',
                    context=None, toolbar=False, submenu=False):
        if context is None:
            context = {}
        res = super(channel_active_wizard, self).fields_view_get(
            cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=False)
        is_allow_agent_activete_id = self.pool.get("ir.config_parameter").search(cr, uid,
                                                                      [('key', '=', 'is_allow_agent_activete')], context=context)
        if is_allow_agent_activete_id:
            is_allow_agent_activete = self.pool.get("ir.config_parameter").browse(
             cr, uid, is_allow_agent_activete_id, context=context)[0].value
            if is_allow_agent_activete=="False":
                raise osv.except_osv(_('Warning!'),
                                 u'您当前不能进行激活操作, 请联系总部！')
        return res

    def parse_text(self, cr, text):
        '''将文本解析为独立的code'''
        text=text.replace(' ','')
        text=text.replace('-','~')
        text=text.replace('－','~')
        text=text.replace('～','~')
        mis = 0 #记录左侧text输入的卡券号所在
        row_code = 0 #记录每行区间共有多少张卡券，防止区间过大导致卡死
        res = [] #存放解析出来的tuple列表，tuple第一个元素为行号，第二个元素为卡券号
        temp_list=text.split('\n')
        for temp in temp_list:
            mis += 1
            from_to = temp.split('~')
            current = from_to[0]
            res.append((mis,current))
            if len(from_to) == 2:
                while current != from_to[1]:
                    current = self.pool['product.card.issue'].get_next_n_number(cr, current,1)
                    res.append((mis,current))
                    row_code += 1
                    #性能 报错
                    if len(current) != len(from_to[1]):
                        raise osv.except_osv(u'警告',u'您输入的第%s行起始和结束卡券位数不一致，请重新输入！' % mis)
                    if current > from_to[1]:
                        raise osv.except_osv(u'警告',u'您输入的第%s行起始卡券号大于结束卡券号，请重新输入！' % mis)
                    if row_code > 999:
                        raise osv.except_osv(u'警告',u'您输第%s行卡券区间超过1000，请修改后再激活！' % mis)
        return res
   
    def product_card_active(self,cr,uid,ids,context=None):#卡券激活操作
        card_line_obj=self.pool.get('product.card.line')
        line_ids = []
        com_text=self.browse(cr,uid,ids,context=context)
        text_list=com_text.check_active.split('\n')
        if len(text_list[0])!=0:
            raise osv.except_osv(u'警告',u'您输入的券号有误，请修改正确后再激活！')
#        for act in self.browse(cr,uid,ids,context=context):
        codes = []
        codes.extend(self.parse_text(cr, com_text.active_number))
        for code in codes:
            line_ids.extend(card_line_obj.search(cr,uid,[('code','=',code), '|', ('active', '=', False), ('active', '=', True)],context=context))
        message = self.pool['product.card.line'].do_active(cr,SUPERUSER_ID,line_ids,context=context)
        if message:
            raise osv.except_osv(u'警告！',message)               
        return True

#卡券销售订单明细查询
class agents_product_card_detail(osv.osv):
    _name = "agents.product.card.detail"
    _description = u'卡券销售订单明细查询'
    _auto = False
    
    _columns = {
        'order_id':fields.many2one('agents.order',u'订单号',readonly=True),
        'send_date':fields.datetime(u'发货日期',readonly=True),
        'state':fields.char(u'状态',readonly=True),
        'partner_id':fields.many2one('res.partner',u'客户',readonly=True),
        'product_id':fields.many2one('product.product', u'产品',readonly=True),
        'shop_coupons_quantity':fields.integer(u'铺券数量',readonly=True),
        'active_quantity':fields.integer(u'激活数量',readonly=True),
        'active_amount':fields.float(u'激活金额',readonly=True),
        'order_type':fields.char(u'订单类别',readonly=True),
        'write_uid':fields.many2one('res.users',u'创建用户',readonly=True),
        'start_number':fields.char(u'起始卡券号码',readonly=True),
        'end_number':fields.char(u'结束卡券号码',readonly=True),
    }

    '''
    建立卡券销售订单明细视图
    将agents_order表和agents_order_line表join得到一个view，通过init方法在每次调用的时候，自动从数据库中获取view
    '''
    def init(self, cr):
        tools.drop_view_if_exists(cr, self._table)
        cr.execute("""CREATE or REPLACE VIEW %s as(
            SELECT aol.id as id,
                ao.id as order_id,
                ao.send_date as send_date,
                ao.state as state,
                ao.customer as partner_id,
                aol.product_id as product_id,
                ao.write_uid as write_uid,
                (case when ao.shop_coupons_order <> True
                then '销售订单'
                else '铺券订单'
                end) as order_type,
                aol.copy_card_start_number as start_number,
                aol.card_end_number as end_number,
                (case when ao.shop_coupons_order =True
                then sum(aol.quantity)
                end) as shop_coupons_quantity,
                (case when ao.active_order = True
                then sum(aol.quantity)
                end) as active_quantity,
                (case when ao.active_order = True
                then sum(aol.total_price)
                end) as active_amount
            FROM agents_order AS ao INNER JOIN agents_order_line AS aol ON ao.id = aol.order_id
            GROUP BY aol.id, ao.id, ao.send_date, ao.state, ao.customer, aol.product_id, ao.write_uid)
        """% (self._table,))
